package com.jw.banddroid.bandsintown;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;

import com.jw.banddroid.exeptions.ApiServerException;

public class Server {

	/**
	 * Location of BandsInTown API
	 */
	private static final String SERVER_URL = "http://api.bandsintown.com";

	/**
	 * Timeout for connections in milliseconds.
	 */
	private static final int TIMEOUT = 30 * 1000;

	private static final String apiId = "banddroid";

	public Server() {

	}

	/**
	 * @param artist
	 * @return
	 * @throws ApiServerException
	 *             , IOException
	 * @throws IOException
	 * @throws OsmServerException
	 */
	public InputStream getStreamForArtist(final String artist)
			throws ApiServerException, IOException {
		URL url = new URL(SERVER_URL + "/events/search?artist[]=" + artist
				+ "?format=xml&app_id=" + apiId);
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		boolean isServerGzipEnabled = false;

		// --Start: header not yet send
		con.setReadTimeout(TIMEOUT);
		con.setConnectTimeout(TIMEOUT);
		con.setRequestProperty("Accept-Encoding", "gzip");

		// --Start: got response header
		isServerGzipEnabled = "gzip".equals(con
				.getHeaderField("Content-encoding"));

		if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
			throw new ApiServerException(con.getResponseCode(),
					"The API server does not except the request: " + con
							+ ", response code: " + con.getResponseCode());
		}

		if (isServerGzipEnabled) {
			return new GZIPInputStream(con.getInputStream());
		} else {
			return con.getInputStream();
		}
	}

	public InputStream getStreamForLocation(final String location)
			throws ApiServerException, IOException {
		URL url = new URL(SERVER_URL + "/events/search?location=" + location
				+ "&format=xml&app_id=" + apiId);
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		boolean isServerGzipEnabled = false;

		// --Start: header not yet send
		con.setReadTimeout(TIMEOUT);
		con.setConnectTimeout(TIMEOUT);
		con.setRequestProperty("Accept-Encoding", "gzip");

		// --Start: got response header
		isServerGzipEnabled = "gzip".equals(con
				.getHeaderField("Content-encoding"));

		if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
			throw new ApiServerException(con.getResponseCode(),
					"The API server does not except the request: " + con
							+ ", response code: " + con.getResponseCode());
		}

		if (isServerGzipEnabled) {
			return new GZIPInputStream(con.getInputStream());
		} else {
			return con.getInputStream();
		}
	}
}
